package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.commom.CustomException;
import com.itheima.reggie.commom.ResultInfo;
import com.itheima.reggie.commom.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.domain.Order;
import com.itheima.reggie.domain.OrderDetail;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.rmi.CORBA.Util;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {


    // 购物车
    @Autowired
    private CartService cartService;

    // 收货地址
    @Autowired
    private AddressMapper addressMapper;

    // 订单
    @Autowired
    private OrderMapper orderMapper;

    // 订单明细
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    // 用户下单
    @Override
    public void submit(Order order) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();

        // 2.获取收货地址对象
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址异常，请重新选择下单");
        }

        // 3.获取购物车对象
        List<Cart> cartList = cartService.list();
        if (CollUtil.isEmpty(cartList)) {
            throw new CustomException("购物车为空，请选择菜品后下单");
        }

        // 雪花id生成订单id
        Long orderId = IdWorker.getId();

        // 订单支付总金额
        BigDecimal orderAmount = new BigDecimal("0");

        // 4.一个购物项=一个订单明细
        for (Cart cart : cartList) {
            // 4-1 封装订单明细
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setImage(cart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            // 4-2 保存订单明细
            orderDetailMapper.insert(orderDetail);
            // 4-3 计算支付总金额   总金额= 总金额+(单价×数量)
            orderAmount = orderAmount.add(orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber())));
        }

        // 5.保存订单
        order.setId(orderId);
        order.setNumber(orderId.toString());
        order.setStatus(1);
        order.setUserId(userId);
        order.setOrderTime(new Date()); // 下单时间
        order.setCheckoutTime(new Date()); // 结账时间
        order.setAmount(orderAmount);
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);

        // 6.清空购物车
        cartService.deleteList();

    }

    //后台订单明细
    @Override
    public Page<Order> page(Integer page, Integer pageSize, String number, LocalDate beginTime, LocalDate endTime) {
        //select * from orders where number = ? | order_time >= beginTime and order_time <= endTime
        //select * from orders where number = ? | betweent beginTime and endTime
        //构造条件
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ObjectUtil.isNotEmpty(number), Order::getNumber, number);
        lqw.ge(ObjectUtil.isNotEmpty(beginTime), Order::getOrderTime, beginTime);
        lqw.le(ObjectUtil.isNotEmpty(endTime), Order::getOrderTime, endTime);
        //设置分页
        Page<Order> pageNum = new Page<>(page, pageSize);
        //查询
        pageNum = orderMapper.selectPage(pageNum, lqw);


        //返回结果
        return pageNum;
    }

}
